<template>
  <div class="register-form">
    <h2>注册</h2>
<!--    HTML 中 <form> 标签在提交时，会默认刷新页面或跳转到 action 指定的地址。
而在 Vue 单页应用（SPA）中，我们是用 JavaScript 处理数据提交，不需要页面跳转-->
    <form @submit.prevent="handleRegister">
      <div>
        <label>手机号：</label>
        <input v-model="phoneFrom.phone"  placeholder="请输入手机号" />
      </div>
      <div>
        <label>验证码：</label>
        <input v-model="registerFrom.code" placeholder="请输入验证码" />
        <button type="button" @click="getCode" :disabled="countdown > 0">
          {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
        </button>
      </div>
      <div>
        <label>设置密码：</label>
        <input v-model="registerFrom.password" type="password" placeholder="请输入密码" />
      </div>
      <button type="submit">注册</button>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import {getMes,register} from '../api/qqUser.js'
import {useRouter} from "vue-router";
const router=useRouter()

const phoneFrom = ref({
  phone:''
})
// 注册用到的数据
const registerFrom=ref({
    phone:'',
    code:'',
    password:''
})

const countdown = ref(0)
let timer = null

// 获取验证码逻辑（模拟）
const getCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(phoneFrom.value.phone)) {
    alert('请输入有效手机号')
    return
  }

 //请求后端获取验证码的接口
  try {
    await  getMes(phoneFrom.value)
    alert('验证码已发送')
    countdown.value = 60
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (err) {
    alert('验证码发送失败')
  }
}

// 注册逻辑
const handleRegister = async () => {
  if (!phoneFrom.value.phone || !registerFrom.value.code || !registerFrom.value.password) {
    alert('请填写完整信息')
    return
  }

  try {
    registerFrom.value.phone=phoneFrom.value.phone;
   const {data}=  await register(registerFrom.value)
    alert(`注册成功,您的账号为--${data}--请记住,点击跳转登录页面`)
    router.push('/login')
  } catch (err) {
    alert('注册失败')
  }
}
</script>

<style scoped>
.register-form {
  max-width: 400px;
  margin: 0 auto;
}
.register-form div {
  margin-bottom: 12px;
}
.register-form input {
  padding: 8px;
  width: 100%;
  box-sizing: border-box;
}
.register-form button {
  padding: 8px 12px;
}
</style>